package com.futvan.z.erp.zproduct;

import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.common.service.CommonService;
import com.futvan.z.framework.core.SuperAction;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.FileUtil;
import com.futvan.z.framework.util.ImgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
@Controller
public class ZproductAction extends SuperAction{
	@Autowired
	private ZproductService zproductService;
	@Autowired
	private CommonService commonService;

	/**
	 * 	重写插入方法
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/z_product_insert")
	public @ResponseBody Result z_form_table_insert(@RequestParam HashMap<String,String> bean) throws Exception {
		String zid = z.newZid("z_product");

		//生成图片
		String img_url = CreateQRCodeImage(zid);
		if(z.isNotNull(img_url)) {
			bean.put("qrcode", img_url);
		}

		return commonService.insert(bean, request);
	}
	
	/**
	 * 	重写修改方法
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/z_product_update")
	public @ResponseBody Result z_form_table_update(@RequestParam HashMap<String,String> bean) throws Exception {
		String zid = bean.get("zid");
		//生成图片
		String img_url = CreateQRCodeImage(zid);
		if(z.isNotNull(img_url)) {
			bean.put("qrcode", img_url);
		}
		return commonService.update(bean, request);
	}
	
	/**
	 * 根据Zid创建二维码文件并上传文件服务器
	 * @param zid
	 * @return
	 * @throws Exception
	 */
	private String CreateQRCodeImage(String zid) throws Exception {
		//二维码图片名称
		String qrcode_name = zid+"_qrcede";

		//二维码URL信息
		String httpHead = "http://";
		if("true".equals(z.sp.get("isSSL"))) {
			httpHead = "https://";
		}
		String url =  httpHead+ z.sp.get("serverip") + "/product_view?zid="+zid;

		//生成二维码图片
		BufferedImage img = ImgUtil.CreateQRCode(url, getWebAppPath()+"img\\zlogin.jpg");
		File imgFile = new File(getWebAppPath()+"temp\\"+qrcode_name+".jpg");
		ImageIO.write(img, "JPG", imgFile);

		//上传二维码图片
		String img_url = FileUtil.UploadFile(qrcode_name, new FileInputStream(imgFile));

		return img_url;
	}

	
}
